package com.wanxi.servlet;

import com.alibaba.fastjson2.JSONObject;
import com.wanxi.VO.UserVO;
import com.wanxi.dto.ResultDTO;
import com.wanxi.service.UserService;
import com.wanxi.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : 林子淳
 * @create 2023/2/23 22:21
 */
//@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.乱码
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        //2.获取前端传到后端的值
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //3.封装到VO
        UserVO userVO = new UserVO();
        userVO.setUsername(username);
        userVO.setPassword(password);
        //4.调用服务逻辑层
        UserService userService = new UserServiceImpl();
        //判断是否登录
        Object attribute = req.getServletContext().getAttribute("username");
        if (attribute != null) {
            ResultDTO resultDTO = new ResultDTO(-1,"账号已在别处登录！",0,null);
            resp.getWriter().println(JSONObject.toJSONString(resultDTO));
        } else {
            //5.得到返回结果
            ResultDTO resultDTO = userService.login(userVO);
            if ("success".equals(resultDTO.getMsg())) {
//            req.getSession().setAttribute("username", username);
                req.getServletContext().setAttribute("username", username);
            }
            //6.返回给前端
            resp.getWriter().println(JSONObject.toJSONString(resultDTO));
        }
    }
}
